package com.mindcraft.shop.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.shop.client.UserClient;
import com.mindcraft.shop.mapper.*;
import com.mindcraft.shop.po.*;
import com.mindcraft.shop.service.MarketTopicSkuService;
import com.mindcraft.shop.vo.MarketTopicSkuVo;
import com.mindcraft.shop.vo.MarketTopicVo;
import com.mindcraft.user.po.McUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MarketTopicSkuServiceImpl extends ServiceImpl<MarketTopicSkuMapper, MarketTopicSku> implements MarketTopicSkuService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private MarketSkuImgMapper marketSkuImgMapper;


    @Autowired
    private MarketHotTopicMapper marketHotTopicMapper;

    @Autowired
    private MarketTopicInnerSortMapper marketTopicInnerSortMapper;

    @Override
    public MindCraftResult getTopicSkuList(MarketTopicSkuVo marketTopicSkuVo) {
        // 分页查询话题列表
        IPage<MarketHotTopic> topicPage = marketHotTopicMapper.selectPage(
                marketTopicSkuVo,
                new LambdaQueryWrapper<MarketHotTopic>().eq(MarketHotTopic::getSource, marketTopicSkuVo.getSource())
        );

        List<MarketHotTopic> topicList = topicPage.getRecords();


        // 将话题列表随机排序
        Collections.shuffle(topicList);

        // 遍历话题列表，为每个话题查询对应的 SKU 列表
        for (MarketHotTopic topic : topicList) {

            //查询出内部分类按钮名字,封装topicInnerSortList
            Integer innerSortId = topic.getInnerSortId();
            if (topic.getInnerSortId() != null) {
                ArrayList<String> topicInnerSortList = new ArrayList<>();

                MarketTopicInnerSort marketTopicInnerSort = marketTopicInnerSortMapper.selectById(innerSortId);

                if (marketTopicInnerSort.getName1() != null && !marketTopicInnerSort.getName1().isEmpty()) {
                    topicInnerSortList.add(marketTopicInnerSort.getName1());
                }
                if (marketTopicInnerSort.getName2() != null && !marketTopicInnerSort.getName2().isEmpty()) {
                    topicInnerSortList.add(marketTopicInnerSort.getName2());
                }
                if (marketTopicInnerSort.getName3() != null && !marketTopicInnerSort.getName3().isEmpty()) {
                    topicInnerSortList.add(marketTopicInnerSort.getName3());
                }
                if (marketTopicInnerSort.getName4() != null && !marketTopicInnerSort.getName4().isEmpty()) {
                    topicInnerSortList.add(marketTopicInnerSort.getName4());
                }
                if (marketTopicInnerSort.getName5() != null && !marketTopicInnerSort.getName5().isEmpty()) {
                    topicInnerSortList.add(marketTopicInnerSort.getName5());
                }
                if (marketTopicInnerSort.getName6() != null && !marketTopicInnerSort.getName6().isEmpty()) {
                    topicInnerSortList.add(marketTopicInnerSort.getName6());
                }
                topic.setTopicInnerSortList(topicInnerSortList);

            }

            //根据人气排行，并查询当前的topic是否是在排行榜前9中，如果在，那就把hotChartsFlag变为true
            LambdaQueryWrapper<MarketHotTopic> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByDesc(MarketHotTopic::getPopularity);
            queryWrapper.last("limit 9");
            List<MarketHotTopic> marketHotTopicList = marketHotTopicMapper.selectList(queryWrapper);

            // 使用带索引的循环方式，以便我们可以获取当前的排名
            for (int i = 0; i < marketHotTopicList.size(); i++) {
                MarketHotTopic item = marketHotTopicList.get(i);
                if (item.getId().equals(topic.getId())) {
                    // 排名是索引+1，因为索引是从0开始的
                    topic.setHotChartsFlag(i + 1);
                    break; // 找到后就可以退出循环了
                }
            }


            List<MarketTopicSku> marketTopicSkus = baseMapper.selectList(
                    new LambdaQueryWrapper<MarketTopicSku>()
                            .eq(MarketTopicSku::getTopicId, topic.getId())
                            .last("limit 4") // 限制每个话题的 SKU 列表最多为 4 条
            );
            marketTopicSkus.stream().forEach((marketTopicSku -> {


                //查询关联的话题，封装topicList
                ArrayList<Integer> topicIdList = new ArrayList<>();
                topicIdList.add(marketTopicSku.getTopicId());
                topicIdList.add(marketTopicSku.getTopicId1());
                List<MarketHotTopic> topicList1 = marketHotTopicMapper.selectBatchIds(topicIdList);
                List<MarketTopicVo> marketTopicVoList = topicList1.stream().map((topicItem) -> {
                    MarketTopicVo marketTopicVo = new MarketTopicVo();
                    marketTopicVo.setTopicId(topicItem.getId());
                    marketTopicVo.setTopicTitle(topicItem.getTitle());
                    return marketTopicVo;
                }).collect(Collectors.toList());
                marketTopicSku.setTopicList(marketTopicVoList);
                //查询图片信息
                MarketSkuImg marketSkuImg = marketSkuImgMapper.selectById(marketTopicSku.getImgId());
                if (marketSkuImg != null) {
                    List<String> imgUrlList = new ArrayList<>();

                    if (marketSkuImg.getImg1() != null) {
                        imgUrlList.add(marketSkuImg.getImg1());
                    }

                    if (marketSkuImg.getImg2() != null) {
                        imgUrlList.add(marketSkuImg.getImg2());
                    }

                    if (marketSkuImg.getImg3() != null) {
                        imgUrlList.add(marketSkuImg.getImg3());
                    }

                    if (marketSkuImg.getImg4() != null) {
                        imgUrlList.add(marketSkuImg.getImg4());
                    }

                    if (marketSkuImg.getImg5() != null) {
                        imgUrlList.add(marketSkuImg.getImg5());
                    }

                    if (marketSkuImg.getImg6() != null) {
                        imgUrlList.add(marketSkuImg.getImg6());
                    }

                    marketTopicSku.setImgUrlList(imgUrlList);
                }
                //查询用户信息
                McUser user = userClient.getUser(marketTopicSku.getUserId());
                marketTopicSku.setPhotoUrl(user.getUserpic());
                marketTopicSku.setNickName(user.getNickname());
            }));
            topic.setMarketTopicSkuList(marketTopicSkus);
        }

        // 将结果封装为返回对象
        MarketTopicSkuVo result = new MarketTopicSkuVo();
        result.setCurrent(topicPage.getCurrent());
        result.setSize(topicPage.getSize());
        result.setTotal(topicPage.getTotal());
        result.setRecords(topicList);

        return MindCraftResult.success(result);
    }

    @Override
    public MindCraftResult getTopicDetail(MarketTopicSkuVo marketTopicSkuVo) {
        //根据话题id 分页查询sku列表,,如果前端点击进入详情，需要去重查询,前端传入点击skuId

        LambdaQueryWrapper<MarketTopicSku> queryWrapper = new LambdaQueryWrapper<MarketTopicSku>()
                .eq(MarketTopicSku::getTopicId, marketTopicSkuVo.getTopicId());
        if (marketTopicSkuVo.getSort() != null) {
            if (marketTopicSkuVo.getSort() == 0) {
                queryWrapper.orderByDesc(MarketTopicSku::getPopularity);
            } else if (marketTopicSkuVo.getSort() == 1) {
                queryWrapper.orderByDesc(MarketTopicSku::getCreateTime);
            }

        }

        IPage<MarketTopicSku> skuPage = baseMapper.selectPage(marketTopicSkuVo, queryWrapper);
        List<MarketTopicSku> skuList = skuPage.getRecords();
        //去除重复数据点击的sku
        if (marketTopicSkuVo.getClickSkuId() != null) {
            skuList = skuList.stream().filter((sku) -> {
                return sku.getId() != marketTopicSkuVo.getClickSkuId();
            }).collect(Collectors.toList());

        }


        for (MarketTopicSku skuItem : skuList) {
            //查询关联的话题，封装topicList
            ArrayList<Integer> topicIdList = new ArrayList<>();
            topicIdList.add(skuItem.getTopicId());
            topicIdList.add(skuItem.getTopicId1());
            List<MarketHotTopic> marketHotTopicList = marketHotTopicMapper.selectBatchIds(topicIdList);
            List<MarketTopicVo> marketTopicVoList = marketHotTopicList.stream().map((topicItem) -> {
                MarketTopicVo marketTopicVo = new MarketTopicVo();
                marketTopicVo.setTopicId(topicItem.getId());
                marketTopicVo.setTopicTitle(topicItem.getTitle());
                return marketTopicVo;
            }).collect(Collectors.toList());
            skuItem.setTopicList(marketTopicVoList);

            //查询每个sku的详情图
            MarketSkuImg marketSkuImg = marketSkuImgMapper.selectById(skuItem.getImgId());
            if (marketSkuImg != null) {
                List<String> imgUrlList = new ArrayList<>();

                if (marketSkuImg.getImg1() != null) {
                    imgUrlList.add(marketSkuImg.getImg1());
                }

                if (marketSkuImg.getImg2() != null) {
                    imgUrlList.add(marketSkuImg.getImg2());
                }

                if (marketSkuImg.getImg3() != null) {
                    imgUrlList.add(marketSkuImg.getImg3());
                }

                if (marketSkuImg.getImg4() != null) {
                    imgUrlList.add(marketSkuImg.getImg4());
                }

                if (marketSkuImg.getImg5() != null) {
                    imgUrlList.add(marketSkuImg.getImg5());
                }

                if (marketSkuImg.getImg6() != null) {
                    imgUrlList.add(marketSkuImg.getImg6());
                }

                skuItem.setImgUrlList(imgUrlList);
            }

            //查询用户信息
            McUser user = userClient.getUser(skuItem.getUserId());
            skuItem.setPhotoUrl(user.getUserpic());
            skuItem.setNickName(user.getNickname());


        }

        // 将结果封装为返回对象
        MarketTopicSkuVo result = new MarketTopicSkuVo();
        result.setCurrent(skuPage.getCurrent());
        result.setSize(skuPage.getSize());
        result.setTotal(skuPage.getTotal());
        result.setRecords(skuList);

        return MindCraftResult.success(result);
    }

    @Override
    public MindCraftResult getSkuListByInnerSort(MarketTopicSkuVo marketTopicSkuVo) {


        lambdaQuery()
                .eq(MarketTopicSku::getSortName, marketTopicSkuVo.getSortName())
                .and(queryWrapper -> queryWrapper.eq(MarketTopicSku::getTopicId, marketTopicSkuVo.getTopicId())
                        .or()
                        .eq(MarketTopicSku::getTopicId1, marketTopicSkuVo.getTopicId())
                )
                .page(marketTopicSkuVo);

        List<MarketTopicSku> records = marketTopicSkuVo.getRecords();
        records.stream().forEach((skuItem) -> {
            //封装用户信息
            McUser user = userClient.getUser(skuItem.getUserId());
            skuItem.setNickName(user.getNickname());
            skuItem.setPhotoUrl(user.getUserpic());


        });

        return MindCraftResult.success(marketTopicSkuVo);
    }

    @Override
    public MindCraftResult getHotRankDetail() {
        //返回一个map，map中半酣了热点话题，最新话题，更多话题
        //map中value为list
        Map<String, List<MarketHotTopic>> resultMap = new HashMap<>();

        // 封装热门话题，根据人气排行
        List<MarketHotTopic> hotTopics = marketHotTopicMapper.selectList(new LambdaQueryWrapper<MarketHotTopic>()
                        .eq(MarketHotTopic::getSort,2)
                .orderByDesc(MarketHotTopic::getPopularity)
                .last("limit 22")
        );
        resultMap.put("hot", hotTopics);

        // 封装最新话题，根据创建时间排行
        List<MarketHotTopic> newTopics = marketHotTopicMapper.selectList(new LambdaQueryWrapper<MarketHotTopic>()

                .orderByDesc(MarketHotTopic::getCreateTime)
                .last("limit 6")
        );
        resultMap.put("new", newTopics);

        // 封装更多话题，随机返回前面已经查询到的话题之外的其他话题
        List<MarketHotTopic> moreTopics = new ArrayList<>();
        List<Integer> excludeIds = new ArrayList<>();  // 记录已经查询到的话题的id，用于排除
        excludeIds.addAll(hotTopics.stream().map(MarketHotTopic::getId).collect(Collectors.toList()));
        excludeIds.addAll(newTopics.stream().map(MarketHotTopic::getId).collect(Collectors.toList()));
        if (excludeIds.size() > 0) {
            List<MarketHotTopic> allTopics = marketHotTopicMapper.selectList(new LambdaQueryWrapper<MarketHotTopic>()
                    .notIn(MarketHotTopic::getId, excludeIds)
                    .last("limit 10"));  // 取前count个
            moreTopics.addAll(allTopics);
        }
        resultMap.put("more", moreTopics);

        return MindCraftResult.success(resultMap);
    }


}
